package com.zthz.douxing.data

import com.zthz.douxing.TaskType
import com.zthz.douxing.TripSegment
import com.zthz.douxing.event.UserWillDepartEvent
import com.zthz.douxing.utils.CommonUtil
import grails.plugin.gson.converters.GSON
import groovy.sql.GroovyResultSet
import groovy.sql.Sql
import org.quartz.JobExecutionContext

import java.sql.SQLException

/**
 * 每天在午夜时分将这一天的要出发的信息抓取出来。然后作为事件发送出来。如果给用户发送失败，要有补发的机制
 * Created by gengjet on 3/30/14.
 */
class SendTrainInfoAndWeathJob {

    def redisKeyGenernateService
    def domainClassInfoService
    def grailsApplication
    def redisService
    def dataSource
    static triggers = {
        //每天执行一次
        cron name: 'searchTodaySendJob', cronExpression: '0 0 */3 * * ?'
    }

    def group = "queryTodayInfoJob"

    def execute(JobExecutionContext context) {

        try {
            if(CommonUtil.isMasterHost()){
                getSegementTrips(context)
            } else {
                log.info("当前主机不是master，忽略这次执行！")
            }
        }catch (Exception e){
            log.debug(e.getMessage(),e)
        }

    }

    private void getSegementTrips(JobExecutionContext context){

        def currentTime = new Date()
        def nextFireTime = context.nextFireTime
        if(!nextFireTime)
            nextFireTime = new Date(currentTime.getTime()+1000*60*60*24)
        if(dataSource){
            String querySql = '''
                     select p.xg_token as xgToken,
                            p.getui_id as geTuiId,
                            s.*,
                            p.username as username
                      from person p, plantrip pt, trip_segment s
                     where s.plantrip_id      = pt.id
                       and pt.person_owner_id = p.id
                       and pt.save_type       = 3
                       and s.segment_status   = 'WillGo'
                       and s.start_time       > ?
                       and s.start_time       < ?
            '''
            try {
                def tripSegmentFieldColumnMap = domainClassInfoService.getFieldColumnMap(TripSegment)
                Sql sql = new Sql(dataSource)
                sql.eachRow(querySql, [ currentTime,  nextFireTime]) { it->
                        if(it){
                            def result = (GroovyResultSet) it
                            TripSegment tripSegment = new TripSegment()
                            tripSegmentFieldColumnMap.each { key, value ->
                                if( key != "plantrip")
                                    tripSegment.getProperties()[key] = it[value]
                            }
                            UserWillDepartEvent willTripEvent = new UserWillDepartEvent()
                            willTripEvent.tripSegment = tripSegment
                            willTripEvent.xgToken = result.getString("xgToken")
                            willTripEvent.getuiId = result.getString("geTuiId")
                            willTripEvent.username = result.getString("username")
                            def willTripEventJson = willTripEvent as GSON
                            def taskQueueName = redisKeyGenernateService.getRedisKey(TaskType.TripWillStartEvent.name(),null)
                            redisService.sendTaskToQueue(taskQueueName, willTripEventJson)
                            log.info(willTripEvent.username+":post")

                        }
                }
            }catch (SQLException e){
                log.error(e.getMessage(), e)
            }
            catch (Exception e){
                log.error(e.getMessage(), e)
            }
        }

    }
}